"""
工具函数模块
包含系统配置、字体设置、API响应格式等通用功能
"""

import sys
import os
import matplotlib.pyplot as plt
import matplotlib
from typing import Any, Optional, Dict


def setup_qt_plugins():
    """设置Qt平台插件路径以解决Windows环境问题"""
    if sys.platform == 'win32':
        try:
            import PyQt5
            pyqt_path = os.path.dirname(PyQt5.__file__)
            plugins_path = os.path.join(pyqt_path, 'Qt5', 'plugins')
            if os.path.exists(plugins_path):
                os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugins_path
        except ImportError:
            pass


def setup_matplotlib_chinese():
    """配置matplotlib支持中文显示"""
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False
    matplotlib.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    matplotlib.rcParams['axes.unicode_minus'] = False


def initialize_system():
    """初始化系统设置"""
    setup_qt_plugins()
    setup_matplotlib_chinese()


# API响应状态码常量
class ResponseCode:
    """统一的响应状态码"""
    SUCCESS = 200
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    FORBIDDEN = 403
    NOT_FOUND = 404
    INTERNAL_ERROR = 500
    SERVICE_UNAVAILABLE = 503


def create_response(code: int, success: bool, message: str, data: Optional[Any] = None) -> Dict[str, Any]:
    """
    创建统一格式的API响应
    
    Args:
        code: 响应状态码 (使用 ResponseCode 常量)
        success: 操作是否成功
        message: 响应消息
        data: 响应数据 (可选)
        
    Returns:
        标准格式的响应字典
    """
    response = {
        "code": code,
        "success": success,
        "message": message
    }
    
    if data is not None:
        response["data"] = data
        
    return response


def success_response(message: str = "操作成功", data: Optional[Any] = None) -> Dict[str, Any]:
    """
    创建成功响应
    
    Args:
        message: 成功消息
        data: 响应数据
        
    Returns:
        成功响应字典
    """
    return create_response(ResponseCode.SUCCESS, True, message, data)


def error_response(message: str, code: int = ResponseCode.BAD_REQUEST, data: Optional[Any] = None) -> Dict[str, Any]:
    """
    创建错误响应
    
    Args:
        message: 错误消息
        code: 错误状态码 (默认400)
        data: 错误数据 (可选)
        
    Returns:
        错误响应字典
    """
    return create_response(code, False, message, data)